﻿#pragma once

#include <string>
#include <sstream>

#include <ace/Svc_Handler.h>
#include <ace/SOCK_Stream.h>
#include <ace/Message_Block.h>


/**
 * 每个连接对应一个ClientHandler。
 */
class WebSocketClientHandler : public ACE_Svc_Handler <ACE_SOCK_STREAM, ACE_NULL_SYNCH>
{
public:
  typedef ACE_Svc_Handler <ACE_SOCK_STREAM, ACE_NULL_SYNCH> super;
  
  
  WebSocketClientHandler (void);
  

  void destroy (void);

  /** 每当有新连接建立的时候，走到这里 */
  virtual int open (void *acceptor);

  virtual int close (u_long flags = 0);

  virtual int handle_close (ACE_HANDLE handle = ACE_INVALID_HANDLE,
                            ACE_Reactor_Mask mask = ACE_Event_Handler::ALL_EVENTS_MASK);
							
protected:

  int svc (void);


  int handle_input (ACE_HANDLE handle);


  int process (char *rdbuf, int rdbuf_len);

  //让destroy方法销毁自己，所以这里是protected
  ~WebSocketClientHandler (void);

  void methodDone();
  void sendReplyMessage(const std::string& reply);
private:
	static const size_t mybufSize=4096;
	ACE_Message_Block mb;
	int parseHandShake();
	int parseData();
	void processMessage(const std::string& req);
	enum State{INIT,HandShake,DataTransfer} state;
	std::ostringstream clientMessageStream;	
	ACE_CString uri;
};							
